package com.soujiayi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.ImageLoader;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

public class UserCenterActivity extends Activity {

	private DatabaseManager databaseManager = new DatabaseManager(
			UserCenterActivity.this);
	private User user;

	private TextView name;
	private TextView gender;
	private TextView city;
	private TextView birthday;
	private ImageView iv_user_photo;
	ProgressDialog progressDialog;
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;
	private static final String IMAGE_FILE_NAME = "faceImage.jpg";
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.user_center);
		initUserInfo();

		progressDialog = new ProgressDialog(UserCenterActivity.this);
		progressDialog.setMessage(getResources().getString(
				R.string.submit_loading));
		progressDialog.setCancelable(false);
		Window window = progressDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.alpha = 0.7f;// 透明度
		lp.dimAmount = 0.5f;// 黑暗度
		window.setAttributes(lp);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if (msg.what == 1) {
					progressDialog.dismiss();
					String url = (String) msg.obj;
					if (url != null && !"".equals(url)) {
						try {
							ImageLoader imageLoader = new ImageLoader(
									UserCenterActivity.this, true, 80, 80, 1);
							imageLoader.DisplayImage(url, iv_user_photo);
							user.setAvatar_url(url);
							databaseManager.updateUserFields(user.getUid(),
									url, null, null, null, null, null);
							UserKeeper.updateUser(UserCenterActivity.this,
									Constants.PREFERENCES_NAME_USER, url, null,
									null, null, null, null);
							Toast.makeText(
									UserCenterActivity.this,
									UserCenterActivity.this
											.getString(R.string.avatar_update_success),
									Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							Toast.makeText(
									UserCenterActivity.this,
									UserCenterActivity.this
											.getString(R.string.avatar_update_fail),
									Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(
								UserCenterActivity.this,
								UserCenterActivity.this
										.getString(R.string.avatar_update_fail),
								Toast.LENGTH_LONG).show();
					}
				}
			}

		};
	}

	public void initUserInfo() {
		name = (TextView) findViewById(R.id.user_center_name);
		gender = (TextView) findViewById(R.id.user_center_gender);
		birthday = (TextView) findViewById(R.id.user_center_birthday);
		city = (TextView) findViewById(R.id.user_center_city);
		iv_user_photo = (ImageView) findViewById(R.id.iv_user_photo);

		user = UserKeeper.readUser(UserCenterActivity.this,
				Constants.PREFERENCES_NAME_USER);
		if (user != null) {
			if (user.getNickname() != null && !"".equals(user.getNickname()))
				name.setText(user.getNickname());

			if (user.getGender() != null && !user.getGender().equals("")) {
				if (user.getGender().equals("1")) {
					gender.setText(this.getResources().getString(R.string.male));
				} else {
					gender.setText(this.getResources().getString(
							R.string.female));
				}
			}

			if (user.getBirthday() != null && !user.getBirthday().equals("")) {
				birthday.setText(user.getBirthday());
			}

			if (user.getCityName() != null && !user.getCityName().equals("")) {
				city.setText(user.getCityName());
			}

			if (user.getAvatar_url() != null
					&& !"".equals(user.getAvatar_url())) {
				ImageLoader imageLoader = new ImageLoader(this, true, 80, 80, 1);
				imageLoader.DisplayImage(user.getAvatar_url(), iv_user_photo);
			}
		}
	}

	public void shareSetting(View view) {
		Intent intent = new Intent(UserCenterActivity.this,
				ShareSettingActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void myProduct_Favorite(View view) {
		if (!NetworkUtils.isNetworkConnected(this)) {
			Toast.makeText(
					UserCenterActivity.this,
					UserCenterActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
			return;
		} else {
			Intent intent = new Intent(UserCenterActivity.this,
					MyFavoriteActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		}
	}

	public void updateAvatar(View view) {
		new AlertDialog.Builder(this)
				.setTitle(this.getString(R.string.update_pic))
				.setItems(
						new String[] {
								this.getString(R.string.pic_from_gallery),
								this.getString(R.string.pic_from_camera) },
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									Intent intentFromGallery = new Intent(
											Intent.ACTION_PICK, null);
									intentFromGallery.setType("image/*"); // 设置文件类型
									startActivityForResult(intentFromGallery,
											IMAGE_REQUEST_CODE);
									break;
								case 1:
									Intent intentFromCapture = new Intent(
											MediaStore.ACTION_IMAGE_CAPTURE);
									// 判断存储卡是否可以用，可用进行存储
									if (CommonUtils.hasSdcard()) {
										intentFromCapture.putExtra(
												MediaStore.EXTRA_OUTPUT,
												Uri.fromFile(new File(
														Environment
																.getExternalStorageDirectory(),
														Constants.STORAGECARD_DIR
																+ "/"
																+ IMAGE_FILE_NAME)));
									}

									startActivityForResult(intentFromCapture,
											CAMERA_REQUEST_CODE);
									break;
								}
							}
						}).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (CommonUtils.hasSdcard()) {
					File tempFile = new File(
							Environment.getExternalStorageDirectory(),
							Constants.STORAGECARD_DIR + "/" + IMAGE_FILE_NAME);
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(UserCenterActivity.this,
							this.getString(R.string.no_sdcard_found),
							Toast.LENGTH_LONG).show();
				}

				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			default:
				break;
			}

			super.onActivityResult(requestCode, resultCode, data);
		}

	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
			final byte[] b = stream.toByteArray();
			progressDialog.show();
			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					String url = new HttpRequester(UserCenterActivity.this)
							.uploadAvatar(
									((MyApplication) UserCenterActivity.this
											.getApplication()).getSessionId(),
									b);
					Message msg = new Message();
					msg.what = 1;
					msg.obj = url;
					handler.sendMessage(msg);
				}
			}).start();

		}
	}

	public void editProfile(View view) {
		Intent intent = new Intent(UserCenterActivity.this,
				EditProfileActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	public void back(View view) {
		Intent intent = new Intent(UserCenterActivity.this,
				SettingActivity.class);
		startActivity(intent);
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	public void logout(View view) {
		if (user != null && user.getUid() > 0)
			databaseManager.deleteUser(String.valueOf(user.getUid()));
		databaseManager.deleteAllFavorites("goods");
		databaseManager.deleteAllFavorites("mall");
		UserKeeper.clear(UserCenterActivity.this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HashMap<String, String> parameters = new HashMap<String, String>();
				parameters.put("sid", ((MyApplication) UserCenterActivity.this
						.getApplication()).getSessionId());
				HttpRequester httpRequester = new HttpRequester(
						UserCenterActivity.this);
				boolean status = httpRequester.logout(parameters, true);
				if (!status)
					status = httpRequester.logout(parameters, true);
			}
		}).start();
		Intent intent = new Intent(UserCenterActivity.this,
				SettingActivity.class);
		startActivity(intent);
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		user = UserKeeper.readUser(UserCenterActivity.this,
				Constants.PREFERENCES_NAME_USER);
		if (user != null) {
			if (user.getNickname() != null && !"".equals(user.getNickname()))
				name.setText(user.getNickname());

			if (user.getGender() != null && !user.getGender().equals("")) {
				if (user.getGender().equals("1")) {
					gender.setText(this.getResources().getString(R.string.male));
				} else {
					gender.setText(this.getResources().getString(
							R.string.female));
				}
			}
			if (user.getBirthday() != null && !"".equals(user.getBirthday()))
				birthday.setText(user.getBirthday());
			if (user.getCityName() != null && !user.getCityName().equals("")) {
				city.setText(user.getCityName());
			}
		}
	}

	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(UserCenterActivity.this,
					SettingActivity.class);
			startActivity(intent);
			this.finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			return false;
		}
		return false;
	}

}
